/*
 * Copyright (C) 2012 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package com.example.google.tv.picasanotifier;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * CheckUpdateService checks every 24 hours if updates have been made to the
 * Picasa albums for any users.
 */
public class CheckUpdateService extends Service {

    private static final String TAG = "CheckUpdateService";

    private static boolean DEBUG = false;

    // Check for update every 24 hours
    private static long CHECK_INTERVAL = 24 * 60 * 60 * 1000;

    private static int mCount = 0;

    private NotificationManager mManager;

    private UserDatabase mUserDb;

    private Cursor mCursor;

    @Override
    public void onCreate() {
        mUserDb = new UserDatabase(this);
        mUserDb.open();
        mManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new CheckForUpdatesTask().execute();
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * Schedule the alarm every 24 hours to check for the albums updates.
     * 
     * @param context Context of the application
     */
    static void scheduleAlarm(Context context) {

        final Intent intent = new Intent(context, CheckUpdateService.class);
        final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
        Calendar c = new GregorianCalendar();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        final AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pending);
        if (DEBUG) {
            alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
                    30 * 1000, pending);
        } else {
            alarm.setRepeating(AlarmManager.RTC, c.getTimeInMillis(), CHECK_INTERVAL, pending);

        }
    }

    /**
     * Check the updates in a separate non-UI thread
     */
    private class CheckForUpdatesTask extends AsyncTask<Void, Object, Void> {
        @Override
        public Void doInBackground(Void... params) {
            try {
                mCursor = mUserDb.getAllNames();
                int id = mCursor.getColumnIndexOrThrow(UserDatabase.KEY_NAME);
                int lastUpdateIndex = mCursor.getColumnIndexOrThrow(UserDatabase.KEY_LASTUPDATE);
                final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
                final Calendar reference = Calendar.getInstance();

                while (mCursor.moveToNext()) {
                    final String username = mCursor.getString(id);
                    calendar.setTimeInMillis(mCursor.getLong(lastUpdateIndex));
                    reference.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                            calendar.get(Calendar.DAY_OF_MONTH),
                            calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE),
                            calendar.get(Calendar.SECOND));
                    final Picasa picasa = Picasa.get();
                    if (picasa.hasUpdates(username, reference)) {
                        mCount++;
                        Log.i("Picasa", "New albums found ");
                    } else {
                        Log.i("Picasa", "No new albums");
                    }
                    final ContentValues values = new ContentValues();
                    values.put(UserDatabase.KEY_LASTUPDATE, System.currentTimeMillis());
                    mUserDb.updateName(id, username, "abc", 1, lastUpdateIndex);
                    mUserDb.close();
                }
                if (mCount > 0) {
                    showNotification(mCount);
                }
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "Column doesn't exist");

            } finally {

                if (mCursor != null) {
                    mCursor.close();
                }
                mUserDb.close();
            }
            return null;
        }

        /**
         * Show notification if there is any new albums
         * 
         * @param mCount number of new albums
         */
        private void showNotification(int mCount) {
            final Intent intent = new Intent(CheckUpdateService.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            Notification notification = new Notification(R.drawable.picasa_icon, "",
                    System.currentTimeMillis());
            notification.setLatestEventInfo(CheckUpdateService.this, mCount + "New albums found",
                    "", PendingIntent.getActivity(CheckUpdateService.this, 0, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT));
            mManager.notify(1, notification);
        }
    }
}
